import React from "react";
import { Button } from "../Button";
import { useChat } from "../../../../store/useChat";
import styles from "./ChatForm.module.css";
import { FileUpload } from "../FileUpload/FileUpload";
import { FileList } from "../FileUpload/FileList";

export const ChatForm: React.FC = () => {
    const currentInput = useChat((state) => state.currentInput);
    const isLoading = useChat((state) => state.isLoading);
    const sendMessage = useChat((state) => state.sendMessage);
    const setCurrentInput = useChat((state) => state.setCurrentInput);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (currentInput.trim() && !isLoading) {
            sendMessage(currentInput);
        }
    };
    const sendButtonDisabled = isLoading || !currentInput.trim();
    const keydownHandler = (e: React.KeyboardEvent) => {
        if (
            e.key === "Enter" &&
            !e.shiftKey &&
            !e.ctrlKey &&
            !e.altKey &&
            !e.metaKey
        ) {
            e.preventDefault();
            handleSubmit(e);
        }
    };
    return (
        <form className={styles.inputArea} onSubmit={handleSubmit}>
            <FileList />
            <div className={styles.inputContainer}>
                <textarea
                    className={styles.input}
                    value={currentInput}
                    onChange={(e) => setCurrentInput(e.target.value)}
                    onKeyDown={keydownHandler}
                    placeholder="输入您的问题..."
                    rows={3}
                    disabled={isLoading}
                />
                <FileUpload />
            </div>
            <Button
                type="submit"
                variant="primary"
                loading={isLoading}
                loadingText="发送中..."
                tooltip="按回车发送"
                disabled={sendButtonDisabled}
                style={{ width: "100%" }}
            >
                发送
            </Button>
        </form>
    );
};
